package com.szwistar.common.comm;

/**
 * Modbus 串口地址
 */
public class ModbusSerialAddress extends SerialAddressEx {
	private static final long serialVersionUID = 2119283945034263043L;

	/// 主机地址
	int hostAddress = 0;
	public int getHostAddress() { return hostAddress; }
	public void setHostAddress(int hostAddress) { this.hostAddress = hostAddress; }

	public ModbusSerialAddress(int hostAddress, String name, int bauds, DataBits dataBits, StopBits stopBits, Parity parity, FlowControl flowControl) {
		super(name, bauds, dataBits, stopBits, parity, flowControl);
		this.hostAddress = hostAddress;
	}

	public ModbusSerialAddress(ModbusSerialAddress another) {
		this(another.getHostAddress(), another.getName(), another.getBauds(), another.getDataBits(), another.getStopBits(), another.getParity(), another.getFlowControl());
	}

	@Override
	public String toString() {
		return hostAddress + "#" + super.toString();
	}

	public static ModbusSerialAddress fromString(String str) throws Exception {
		// 参数格式为: "UART1:115200,8,n,1"
		String[] parts = str.split("[#]");
		if((parts == null) || (parts.length != 2)) {
			throw new Exception("非法的串口参数: " + str);
		}

		int hostAddress = Integer.parseInt(parts[0]);
		SerialAddressEx addr = SerialAddressEx.fromString(parts[1]);
		return new ModbusSerialAddress(hostAddress, addr.getName(), addr.getBauds(), addr.getDataBits(), addr.getStopBits(), addr.getParity(), addr.getFlowControl());
	}
}
